package org.unicamp.gesture;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;

public class GestureActivity extends Activity {
	private Paint mPaint;
	private MyView mView;
	private int signatureNumber = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		createView(this);
	}

	private void createView(Context c) {
		mView = new MyView(this);
		setContentView(mView);

		mPaint = new Paint();
		mPaint.setAntiAlias(true);
		mPaint.setDither(true);
		mPaint.setColor(0xFFFF0000);
		mPaint.setStyle(Paint.Style.STROKE);
		mPaint.setStrokeJoin(Paint.Join.ROUND);
		mPaint.setStrokeCap(Paint.Cap.ROUND);
		mPaint.setStrokeWidth(12);
	}

	public void colorChanged(int color) {
		mPaint.setColor(color);
	}

	private class MyView extends View {

		private Bitmap mBitmap;
		private Canvas mCanvas;
		private Path mPath;
		private Paint mBitmapPaint;

		public MyView(Context c) {
			super(c);

			mBitmap = Bitmap.createBitmap(320, 480, Bitmap.Config.ARGB_8888);
			mCanvas = new Canvas(mBitmap);
			mPath = new Path();
			mBitmapPaint = new Paint(Paint.DITHER_FLAG);
		}

		@Override
		protected void onSizeChanged(int w, int h, int oldw, int oldh) {
			super.onSizeChanged(w, h, oldw, oldh);
		}

		@Override
		protected void onDraw(Canvas canvas) {
			canvas.drawColor(0xFFAAAAAA);

			canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
			canvas.drawPath(mPath, mPaint);
		}

		private float mX, mY;
		private static final float TOUCH_TOLERANCE = 4;

		private void touch_start(float x, float y) {
			mPath.reset();
			mPath.moveTo(x, y);
			mX = x;
			mY = y;
		}

		private void touch_move(float x, float y) {
			float dx = Math.abs(x - mX);
			float dy = Math.abs(y - mY);
			if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
				mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
				mX = x;
				mY = y;
			}
		}

		private void touch_up() {
			mPath.lineTo(mX, mY);
			// commit the path to our offscreen
			mCanvas.drawPath(mPath, mPaint);
			// kill this so we don't double draw
			mPath.reset();
		}

		@Override
		public boolean onTouchEvent(MotionEvent event) {
			float x = event.getX();
			float y = event.getY();

			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				touch_start(x, y);
				invalidate();
				break;
			case MotionEvent.ACTION_MOVE:
				touch_move(x, y);
				invalidate();
				break;
			case MotionEvent.ACTION_UP:
				touch_up();
				invalidate();
				break;
			}
			return true;
		}
		
		public void saveSignature() {
			String path = Environment.getExternalStorageDirectory().toString();
			path = path + "/gsapp/";
			File folder = new File(path);
			folder.mkdirs();
			File imageFile = new File(folder, signatureNumber + ".png");
			FileOutputStream out;
			try {
				out = new FileOutputStream(imageFile);
				mBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
				signatureNumber++;
				out.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	public static void eraseSignatures(){
		String path = Environment.getExternalStorageDirectory().toString();
		path = path + "/gsapp/";
		File folder = new File(path);
		int i = -1;
		File imageFile;
		do {
			i++;
			imageFile = new File(folder, i + ".png");
		} while(imageFile.delete());
	}

	private static final int SAVE_SIGNATURE_ID = Menu.FIRST;
	private static final int FINALIZE_ID = Menu.FIRST + 1;
	private static final int CANCEL_ID = Menu.FIRST + 2;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		menu.add(0, SAVE_SIGNATURE_ID, 0, "Próxima Assinatura").setShortcut(
				'3', 's');
		menu.add(0, FINALIZE_ID, 0, "Finalizar").setShortcut('4', 's');
		menu.add(0, CANCEL_ID, 0, "Cancela").setShortcut('5', 'c');

		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		mPaint.setXfermode(null);
		mPaint.setAlpha(0xFF);

		switch (item.getItemId()) {
		case SAVE_SIGNATURE_ID:
			mView.saveSignature();
			createView(this);
			return true;
		case FINALIZE_ID:
			mView.saveSignature();
			Intent intent = new Intent(this, MainActivity.class);
			startActivityForResult(intent, 0);
			return true;
		case CANCEL_ID:
			eraseSignatures();
			intent = new Intent(this, MainActivity.class);
			startActivityForResult(intent, 0);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}